package com.seele.tigerwallet.ui.activtiy;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Handler;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.v4.hardware.fingerprint.FingerprintManagerCompat;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.seele.base.utils.ToastUtils;
import com.seele.tigerwallet.R;
import com.seele.tigerwallet.async.Log;
import com.seele.tigerwallet.ui.MainActivity;
import com.seele.tigerwallet.ui.base.BaseActivity;
import com.seele.tigerwallet.ui.callback.OnFinishListener;
import com.seele.tigerwallet.ui.manager.KeyDialogManager;
import com.seele.tigerwallet.ui.manager.fingerprint.FingerprintUtil;
import com.seele.tigerwallet.ui.manager.fingerprint.KeyguardLockScreenManager;
import com.seele.tigerwallet.ui.manager.fingerprint.core.FingerprintCore;
import com.seele.tigerwallet.ui.utils.BaseDialog;
import com.seele.tigerwallet.ui.utils.FingerprintUtils;
import com.seele.tigerwallet.ui.utils.KeyBoardUtils;
import com.seele.tigerwallet.ui.utils.PermissionFail;
import com.seele.tigerwallet.ui.utils.PermissionSuccess;
import com.seele.tigerwallet.ui.utils.PermissionUtil;
import com.seele.tigerwallet.ui.utils.SPUtils;
import com.seele.tigerwallet.ui.views.KeyboardView;
import com.seele.tigerwallet.ui.views.PasswordInputView;
import com.seele.tigerwallet.utils.EthWalletUtil;

import java.lang.reflect.Method;
import java.util.List;

import static com.seele.tigerwallet.ui.activtiy.SystemSetActivtiy.SYSTEMSETACTIVTIY;

public class UnlockingActivity extends BaseActivity {

    private FingerprintUtils mFingerprintUtils;
    private BaseDialog mBaseDialog;
    private final int PER_CAMERA = 6;
    public static final int REQUEST_CODE = 0X200;
    private TextView mPasswordLogin;
    private TextView mTitleTv;
    private TextView mContentTv;
    private TextView mPWTv;
    private ImageView mFtImg;
    private KeyDialogManager mKeyDialogManager;
    private LinearLayout mFingerprintLl;

    private TextView mHint;

    private int mFailedTimes;
    private int flag = 0;
    private int mCount = 0;
    private KeyguardLockScreenManager mKeyguardLockScreenManager;

    private Vibrator mVibrator;

    private static final String ACTION_SETTING = "android.settings.SETTINGS";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_unlocking;
    }

    @Override
    protected void init() {
        initWidow();
        mVibrator = (Vibrator) this.getSystemService(this.VIBRATOR_SERVICE);

        initView();

        initDialog();
        if (null == mKeyDialogManager) {
            mKeyDialogManager = new KeyDialogManager(this, 6);
        }
        mKeyDialogManager.initKeyDialog();
        mKeyDialogManager.setOnFinishListener(onFinishListener);
        if (null == mKeyguardLockScreenManager) {
            mKeyguardLockScreenManager = new KeyguardLockScreenManager(this);
        }
        if (null == mFingerprintUtils) {
            mFingerprintUtils = new FingerprintUtils();
        }
        mFingerprintUtils.init(this);
        setFingerprint();


        // 设置不调用系统键盘

        this.getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        mKeyDialogManager.getInputView().setInputType(InputType.TYPE_NULL);


    }



    @Override
    protected void onResumed() {
        Log.e("onResumed", "::onResumed:");
        PermissionUtil.needPermission(this, PER_CAMERA, Manifest.permission.USE_FINGERPRINT);
        super.onResumed();
    }

    @Override
    protected void onPaused() {
        mFailedTimes = 0;
        mFingerprintUtils.clearFingerprintListener();
        super.onPaused();
    }

    /**
     * 指纹时间回调
     */
    private void setFingerprint() {
        mFingerprintUtils.setFingerprintListener(new FingerprintUtils.OnFingerprintListener() {
            @Override
            public void onHardwareDetected(boolean hardwareDetected) {


            }

            @Override
            public void onEnrolledFingerprints(boolean b) {
            }

            @Override
            public void onAuthenticationError(int errorCode, CharSequence errString) {
                Log.e("setFingerprint", ":::onAuthenticationError");
                if (errorCode == 7) {
                    setFailedTimes(errorCode);
                }
            }

            @Override
            public void onAuthenticationHelp(int helpCode, CharSequence helpString) {
                if (helpCode == 1001) {
                    if (null != mBaseDialog) {
//                        mFingerprintUtils.cancel();
                        mBaseDialog.show();
                    }
                }
            }

            @Override
            public void onAuthenticationSucceeded(FingerprintManagerCompat.AuthenticationResult result) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (null != mBaseDialog) {
                            mBaseDialog.dismiss();
                            if (flag == REQUEST_CODE) {
                                onResulIntent(true);
                            } else {
                                startMain();
                            }
                        }
                    }
                }, 600);
            }

            @Override
            public void onAuthenticationFailed() {
                mFailedTimes++;
                setFailedTimes(mFailedTimes);


            }
        });
    }

    private void onResulIntent(boolean isSuccess) {
        Intent resultIntent = new Intent();
        resultIntent.putExtra(SYSTEMSETACTIVTIY, isSuccess);
        setResult(Activity.RESULT_OK, resultIntent);
        if (null!=mKeyDialogManager){
            mKeyDialogManager.dismiss();
        }
        if (null!=mBaseDialog){
            mBaseDialog.dismiss();
        }
        finish();
    }


    private void startMain() {
        if (null!=mKeyDialogManager){
            mKeyDialogManager.dismiss();
        }
        if (null!=mBaseDialog){
            mBaseDialog.dismiss();
        }
        startActivity(MainActivity.class);
        finish();

    }


    OnFinishListener onFinishListener = new OnFinishListener() {
        @Override
        public void onPasswordFinished(final CharSequence text) {
            if (TextUtils.isEmpty(text)) {
                return;
            }

            if (null != mKeyDialogManager) {
                mKeyDialogManager.hideKeyboard();
            }

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    //解锁keystore
                    boolean isRight = EthWalletUtil.checkPassowrd(text.toString());
                    if (isRight) {
                        if (flag == REQUEST_CODE) {
                            onResulIntent(true);
                        } else {
                            startMain();
                        }
                    } else {
                        ToastUtils.showLong(getResources().getText(R.string.password_error));
                    }
                }
            },80);



        }
    };
    Animation shake;

    private void setFailedTimes(int mFailedTimes) {
        if (mFailedTimes <= 3) {
            mVibrator.vibrate(500);
            mFingerprintLl.startAnimation(shake);
            mTitleTv.setText(getResources().getText(R.string.do_it_again));
            mPWTv.setVisibility(View.VISIBLE);
        } else {
            if (null != mBaseDialog) {
                mBaseDialog.dismiss();
            }
            mFingerprintUtils.clearFingerprintListener();
            mHint.setText(getResources().getText(R.string.fingerprint_hint));
            mHint.setTextColor(getResources().getColor(R.color.color_FC6262));
        }

    }


    private void initView() {


        flag = getIntent().getIntExtra(UnlockingActivity.class.getSimpleName(), 0);
        mPasswordLogin = findViewById(R.id.password_login);
        mPasswordLogin.setOnClickListener(onClickListener);
        mFtImg = findViewById(R.id.ft_img);
        mHint = findViewById(R.id.hint_tv);
        mFtImg.setOnClickListener(onClickListener);
        shake = AnimationUtils.loadAnimation(this, R.anim.shake);


    }


    @PermissionSuccess(requestCode = PER_CAMERA)
    private void grantPermissionSuccess() {
        startFingerprint();
    }

    private void startFingerprint() {
        if (mFingerprintUtils.hasEnrolledFingerprints()) {//指纹库有指纹
            show();
            mFingerprintUtils.handlerFingerprint();
        } else {
            setFingerprintDialog();
        }
    }


    /**
     * 设置指纹库没有指纹的样式
     */
    private void setFingerprintDialog() {
        if (null != mBaseDialog) {
            mBaseDialog.show();
            mTitleTv.setText(getResources().getString(R.string.move_to_the_security_center));
            mContentTv.setVisibility(View.GONE);
        }
    }

    public void show() {
        if (null != mBaseDialog && !mBaseDialog.isShowing()) {
            mBaseDialog.show();
        }

    }


    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.cancel:
                    if (null != mBaseDialog && mBaseDialog.isShowing()) {
                        mBaseDialog.dismiss();
                    }
                    if (null != mKeyDialogManager) {
                        mKeyDialogManager.dismiss();

                    }
                    if (flag == REQUEST_CODE) {
                        onResulIntent(false);
                    }

                    break;
                case R.id.transaction_pwd:
                    if (null != mBaseDialog && mBaseDialog.isShowing()) {
                        mBaseDialog.dismiss();
                    }
                    if (null != mKeyDialogManager) {
                        mKeyDialogManager.show();
                    }

                    break;

                case R.id.password_login:
                    if (null != mBaseDialog) {
                        mBaseDialog.dismiss();
                    }
                    if (null != mKeyDialogManager) {
                        mKeyDialogManager.show();
                    }
                    break;

                case R.id.ft_img:
//                    if (null != mKeyDialogManager) {
//                        mKeyDialogManager.dismiss();
//                    }
//                    if (null != mBaseDialog) {
//                        mContentTv.setText(getResources().getText(R.string.fingerprint_title));
//                        mBaseDialog.show();
//                        mFingerprintUtils.init(UnlockingActivity.this);
//                        mFingerprintUtils.handlerFingerprint();
//                    }

                    break;
            }

        }
    };


    /**
     * 初始化Dialo
     */
    private void initDialog() {
        if (null == mBaseDialog) {
            mBaseDialog = new BaseDialog.Builder(this).view(R.layout.dialog_fingerprint)
                    .setDialogPosition(Gravity.CENTER) //设置dialog显示位置
                    .cancelTouchout(false)//点击dialog背景不能取消dialog，默认为true

                    .setWidthPX((int) getResources().getDimension(R.dimen.dp_270))
                    .setHeightPX( WindowManager.LayoutParams.WRAP_CONTENT)
                    .addViewOnclick(R.id.cancel, onClickListener)
                    .addViewOnclick(R.id.transaction_pwd, onClickListener)
                    .build();
            mBaseDialog.setCancelable(false);
        }
        mTitleTv = mBaseDialog.findView(R.id.title_tv);
        mContentTv = mBaseDialog.findView(R.id.content_tv);
        mPWTv = mBaseDialog.findView(R.id.transaction_pwd);
        mFingerprintLl = mBaseDialog.findView(R.id.fingerprint_ll);
        mPWTv.setVisibility(View.GONE);
    }


    @PermissionFail(requestCode = PER_CAMERA)
    private void grantPersmissionFail() {
        Toast.makeText(this, getResources().getString(R.string.read_external_storage), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionUtil.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }


    public void openFingerPrintSettingPage(Context context) {
        Intent intent = new Intent(ACTION_SETTING);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            startActivityForResult(intent, 50);
        } catch (Exception e) {
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {


        Log.e("onActivityResult", "接收数据");
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        if (null != mFingerprintUtils) {
            mFingerprintUtils = null;
        }
        if (null != mBaseDialog) {
            mBaseDialog = null;
        }
        System.gc();
        ;
        super.onDestroy();
    }
}
